package com.stack.common.utils;

import java.util.ArrayList;
import java.util.List;

public final class PageUtil {
  
  private PageUtil () {
    
  }
   
    /**
     * 开始分页
     *
     * @param list
     * @param pageNum  页码
     * @param pageSize 每页多少条数据
     * @return
     */
    public static <T> List<T> startPage(List<T> list, Integer pageNum, Integer pageSize) {
        if(list == null || list.isEmpty()){
            return new ArrayList<T>();
        }
        if (pageNum == null || pageSize == null) {
            return list;
        }
        int a = pageNum -1;
        float b = (float)list.size() / pageSize;
        if( a >= b) {
          return new ArrayList<T>();
        }
        
        Integer count = list.size(); //记录总数
        
        Integer pageCount = 0; //页数
        if (count % pageSize == 0) {
            pageCount = count / pageSize;
        } else {
            pageCount = count / pageSize + 1;
        }
 
        int fromIndex = 0; //开始索引
        int toIndex = 0; //结束索引
 
        if (pageNum != pageCount) {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = fromIndex + pageSize;
        } else {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = count;
        }
        return  list.subList(fromIndex, toIndex);
    }
 
}